# -*- coding: utf-8 -*-
#coding = utf-8

'''
Created on June 3, 2013

@author: Tong Zhang

the basic method for the redis include: key , value , list , pipeline 
            will include : sort set for the social
'''

import redis
import logging
import tcp_config as config

''' 
REDISHOST = "192.168.1.101"
REDISPORT = 6379
REDISDB = 2
'''

''' 
REDISHOST = '42.121.54.224'#"192.168.1.101"
REDISPORT = 6379
REDISDB = 2
'''

class RedisManage:

    pool = redis.ConnectionPool(host=config.REDISHOST, port=config.REDISPORT, db= config.REDISDB)
    @staticmethod
    def __setup_redis():
        client = redis.Redis(connection_pool = RedisManage.pool)
        return client

    @staticmethod
    def check_exists_key(key):
        """
            return a boolean indicating whether key exists
        """
        return RedisManage.__setup_redis().exists(key)

    @staticmethod
    def add_object_to_str(key, value, time = 0):
        """
            set a pair of key/value to SET.
        """
        RedisManage.__setup_redis().set(key, value)
        return True if time == 0 else RedisManage.add_expire_time(key, time)

    @staticmethod
    def get_object_to_str(key):
        """
            get a pair of key/value to SET.
        """
        return RedisManage.__setup_redis().get(key)

    @staticmethod
    def get_active_keys(key):
        return RedisManage.__setup_redis().keys(key)

    @staticmethod
    def append_object_to_list(key, value, on="l", time=0):
        """
            append a value to a LIST.
        """
        result = False
        if str.lower(on) == "l":
            if RedisManage.__setup_redis().lpush(key, value):
                result = True if time == 0 else RedisManage.add_expire_time(key, time)
            return result
        else:
            if RedisManage.__setup_redis().rpush(key, value):
                result = True if time == 0 else RedisManage.add_expire_time(key, time)
            return result

    @staticmethod
    def del_active_key(key):
        return RedisManage.__setup_redis().delete(key)

    @staticmethod
    def get_objects_from_list(key):
        """
            return all values from LIST.
        """
        list = RedisManage.get_object_from_list_by_range_on_left(key, 0, -1)
        return list

    @staticmethod
    def get_object_from_list_by_range_on_left(key, start, end):
        """
            return a slice of the LIST between position start and end.
        """
        return RedisManage.__setup_redis().lrange(key, start, end)

    @staticmethod
    def remove_object_from_list(key, value):
        """
            remove the specific value from list.
        """
        return RedisManage.__setup_redis().lrem(key, value)

    @staticmethod
    def add_expire_time(key, time):
        """
            add an expire time for any Redis key.
        """
        return RedisManage.__setup_redis().expire(key,time)

    @staticmethod
    def get_pipeline(pvalue,time = 0):
        logger = logging.getLogger('et.kernel.tcp.RedisManage.pipeline')
        pipe = RedisManage.__setup_redis().pipeline(transaction=False)
        try:
            if type(pvalue) == type({}):
                for k,v in pvalue.items():
                    if type(v) == type(list()):
                        for value in v:
                            pipe.lpush(k,value)
                        if time != 0:
                            pipe.expire(k,time)
                    elif type(v) == type(set()):
                        for value in v:
                            pipe.sadd(k,value)
                        if time != 0:
                            pipe.expire(k,time)
                    else:
                        pipe.set(k,v)
                        if time != 0:
                            pipe.expire(k,time)

                return pipe.execute()
            elif type(pvalue) == type([]):
                for s in pvalue:
                    pipe.delete(s)

                return pipe.execute()


        except Exception, e:
            logger.error(e)
    

    @staticmethod
    def add_object_to_sets(key, value, time=0):
        """
            add a pair of key/value to SETS.
        """
        result = False
        if RedisManage.__setup_redis().sadd(key, value):
            result = True if time == 0 else RedisManage.add_expire_time(key, time)
        return result

    @staticmethod
    def add_objects_to_sets(key, list_value, time=0):
        for value in list_value:
            RedisManage.__setup_redis().sadd(key, value)
        return True if time == 0 else RedisManage.add_expire_time(key, time)

    @staticmethod
    def remove_object_from_sets(key, value):
        """
            remove a pair of key/value from SETS with specific key.
        """
        return RedisManage.__setup_redis().srem(key, value)

    @staticmethod
    def get_objects_from_sets(key):
        """
            return all values from SETS with specific key.
        """
        return list(RedisManage.__setup_redis().smembers(key))

    @staticmethod
    def check_object_from_sets(key, value):
        """
             check the object exist in sets, return True or False
        """
        return RedisManage.__setup_redis().sismember(key, value)

 



